package com.software.loginregister.databasesHelper;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.software.loginregister.entity.ConversationHistory;

import java.util.ArrayList;
import java.util.List;

public class SQLiteHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "conversations.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "conversations";
    private static final String COLUMN_TIMESTAMP = "timestamp";

    public SQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE conversations (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "name TEXT, " +
                "timestamp INTEGER)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public void addConversation(String name, Long timestamp) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("timestamp", timestamp);
        db.insert("conversations", null, values);
        db.close();
    }

    public List<ConversationHistory> getAllConversations() {
        List<ConversationHistory> conversations = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query("conversations", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
                @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
                @SuppressLint("Range") Long createdAt = cursor.getLong(cursor.getColumnIndex("timestamp"));

                ConversationHistory conversation = new ConversationHistory();
                conversation.setId(String.valueOf(id));
                conversation.setName(name);
                conversation.setCreatedAt(createdAt);

                conversations.add(conversation);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return conversations;
    }
}
